package com.linghui.videoplus.ipai.activity;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.linghui.videoplus.ipai.R;
import com.linghui.videoplus.ipai.VideoPlusApplication;

public class BrowserActivity extends BaseActivity implements OnClickListener{
	
	
	private WebView webView = null;
	private ProgressBar progressBar = null;
	private ProgressDialog pd = null;
	private Handler handler = null;

	private String url=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_browser);
		
		if(!VideoPlusApplication.checkNetWorkStatus(this)){
			showToast(this.getResources().getString(R.string.network_error));
			NetWorkErrorActivity.launch(this, REQUEST_CODE_DEFAULT, REQUEST_CODE_NETWORK_ERROR);
		}
		FROM_CODE = getIntent().getIntExtra(FROM_CODE_KEY, REQUEST_CODE_DEFAULT);
		url = getIntent().getStringExtra("url");
		
		menuLayout = (com.linghui.videoplus.ipai.view.MenuLayout) this.findViewById(R.id.menuLayout);
		menuLayout.setOnClickListener(this);
		menuLayout.setFocus(R.id.homeLL);
		
		progressBar = (ProgressBar) findViewById(R.id.WebketProgressBar);
		webView = (WebView) findViewById(R.id.WebView01);
		WebSettings webSettings = webView.getSettings();  
		webSettings.setJavaScriptEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setAllowFileAccess(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setUseWideViewPort(true);
		webSettings.setAppCacheEnabled(true); 
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
		webSettings.setAppCacheMaxSize(1024*1024*8);
		
		pd = new ProgressDialog(BrowserActivity.this);
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pd.setMessage("载入中,请稍候..."+progressBar.getProgress()+"%");
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (!Thread.currentThread().isInterrupted()) {
					switch (msg.what) {
					case 0:
						if(pd!=null){
							pd.show(); 
						}
						break;
					case 2:
						if(pd!=null){
							pd.setMessage("载入中,请稍候..."+progressBar.getProgress()+"%");
						}
						break;
					case 1:
						if(pd!=null){
							pd.hide(); 
						}
						break;
					case 100:
						String url = (String) msg.obj;
						
						if(getRespStatus(url)==200) {
							webView.loadUrl(url);
						}else{
							webView.stopLoading();
							NetWorkErrorActivity.launch(BrowserActivity.this, REQUEST_CODE_DEFAULT, REQUEST_CODE_NETWORK_ERROR);
						}
						break;
					}
				}
				super.handleMessage(msg);
			}
		};
		
		// 设置下载监听
		webView.setDownloadListener(new DownloadListener() {
			@Override
			public void onDownloadStart(String url, String userAgent,
					String contentDisposition, String mimetype,
					long contentLength) {
				parserUrl(url);
			}
			
		});
		
		// 设置WebViewClient
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				
				if(getRespStatus(url)==200) {
					excuteWebViewLoadUrl(url);
				}else{
					view.stopLoading();
					NetWorkErrorActivity.launch(BrowserActivity.this, REQUEST_CODE_DEFAULT, REQUEST_CODE_NETWORK_ERROR);
				}
				return true;
			}

		});
		
		// 设置WebChromeClient
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				// 更新进度
				progressBar.setProgress(newProgress);
				if (newProgress >= 95) {
					handler.sendEmptyMessage(1); 
					progressBar.setProgress(0);
					progressBar.setVisibility(view.GONE);
				}else{
					handler.sendEmptyMessage(2); 
				}
				super.onProgressChanged(view, newProgress);
			}
		});
		excuteWebViewLoadUrl(url);
		
	}
	/**解析URL
	 * show!play.action?execute=2&name=1111.mp4&desc=xx&img=xx
	   execute=1下载;execute=2播放;execute=3直播
	 * @param url
	 * @return
	 */
	private boolean parserUrl(final String url) {
		try {	
			int index = url.indexOf("?");
			String videoUrl=null;
			HashMap<String, String> pm = new HashMap<String, String>();
			if (index > 0 && index < url.length() - 1) {
				videoUrl = url.substring(0, index);
				String attrib = url.substring(index + 1);
				String[] parameter = attrib.split("&");
				for (String p : parameter) {
					String[] v = p.split("=");
					pm.put(v[0], v[1]);
				}
			}
			if (url.indexOf("execute=1") != -1 || url.indexOf("execute=2") != -1) {
					// URL参数
					String name = pm.get("name");
					String detail = pm.get("detail");
					if (name != null && name.length() > 0) {
						name=URLDecoder.decode(name,"utf-8");
					}
					if (detail != null && detail.length() > 0) {
						detail=URLDecoder.decode(detail);
					}
					PlayerActivity.launch(this, videoUrl,name,detail, true);
					return true;
			} else if (url.indexOf("execute=3") != -1) {
				Uri uri = Uri.parse(url);
				Intent it = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(it);
				return true;
			} else if (url.indexOf("execute=4") != -1) {
				String name = pm.get("name");
				String detail = pm.get("detail");
				if (name != null && name.length() > 0) {
					name=URLDecoder.decode(name);
				}
				if (detail != null && detail.length() > 0) {
					detail=URLDecoder.decode(detail);
				}
				String content="精彩微视频："+name+":"+detail+"；分享来自@看看微视频。";
				Intent intent = new Intent(Intent.ACTION_SEND);
				intent.setType("text/plain");
				intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
				intent.putExtra(Intent.EXTRA_TEXT, content);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(Intent.createChooser(intent, getTitle()));
				return true;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	/**
	 * 
	 * @param url
	 */
	public void excuteWebViewLoadUrl(final String url) {
		if (url == null) {
			return;
		}
		
		
		if (!parserUrl(url)) {
			// 执行打开连接
			new Thread() {
				public void run() {
					// 非初始化显示进度状态
					handler.sendEmptyMessage(0);
					Message msg = new Message();
					msg.what = 100;
					msg.obj = url;
					handler.sendMessage(msg);
				}
			}.start();
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(FROM_CODE==REQUEST_CODE_SETTING){
				this.setResult(RESULT_OK, getIntent());
				this.finish();
			}else{
				if (webView.canGoBack()) {
					webView.goBack();
					return true;
				}else{
					VideoPlusApplication.exitApplication(this);
					return false;
				}
			}
		}
		return true;
	}	
	
	@Override
	public void onClick(View v) {
		int vId=v.getId();
		
		if(vId==R.id.photoLL||vId==R.id.photoImageView){
			VideoCascadeActivity.launch(this, REQUEST_CODE_DEFAULT,REQUEST_CODE_VIDEO_CASCADE);
		}else if(vId==R.id.cameraLL||vId==R.id.cameraImageView){
			CameraActivity.launch(this, REQUEST_CODE_DEFAULT,REQUEST_CODE_CAMERA);
		}else if(vId==R.id.homeLL||vId==R.id.homeImageView){
			BrowserActivity.launch(this,VideoPlusApplication.getUrlIndex(this),REQUEST_CODE_DEFAULT, REQUEST_CODE_DEFAULT);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		pd.dismiss();
	}
	
	private int getRespStatus(String url) {
        int status = -1;
        try {
            HttpHead head = new HttpHead(url);
            HttpClient client = new DefaultHttpClient();
            HttpResponse resp = client.execute(head);
            status = resp.getStatusLine().getStatusCode();
        } catch (IOException e) {
        	return status;
        }
        return status;
	}
	
	
	public static void launch(Activity mActivity,String url,int fromCode,int toCode) {
		Intent intent = new Intent(mActivity, BrowserActivity.class);
		intent.putExtra("url", url);
		intent.putExtra(FROM_CODE_KEY, fromCode);
		intent.putExtra(TO_CODE_KEY, toCode);
		mActivity.startActivity(intent);
		mActivity.finish();
	}
	
}
